Imports MIMS.WRS.Entities
Imports MIMS.WRS.Business

Public Class UserDetail1
    Inherits System.Web.UI.UserControl

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents ltrMessage As System.Web.UI.WebControls.Literal
    Protected WithEvents txtLoginName As System.Web.UI.WebControls.TextBox
    Protected WithEvents Requiredfieldvalidator2 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlUserType As System.Web.UI.WebControls.DropDownList
    Protected WithEvents btnOK As System.Web.UI.WebControls.Button
    Protected WithEvents btnDelete As System.Web.UI.WebControls.Button
    Protected WithEvents btnCancel As System.Web.UI.WebControls.Button
    Protected WithEvents chkChangePass As System.Web.UI.WebControls.CheckBox
    Protected WithEvents chkOffices As System.Web.UI.WebControls.CheckBoxList
    Protected WithEvents ddlCountry As System.Web.UI.WebControls.DropDownList
    Protected WithEvents reqvCountry As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents txtFullPassword As System.Web.UI.WebControls.TextBox
    Protected WithEvents chkViewSalesOrders As System.Web.UI.WebControls.CheckBox

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Protected mainObj As USER = Nothing

    Protected Property ReferrerUrl() As String
        Get
            Return Convert.ToString(ViewState("ReferrerUrl"))
        End Get
        Set(ByVal Value As String)
            ViewState("ReferrerUrl") = Value
        End Set
    End Property

    Protected ReadOnly Property IsAddNew() As Boolean
        Get
            Return RequestContext.UserID = -1
        End Get
    End Property

    Private Function BuildObject() As Boolean
        If IsAddNew Then
            mainObj = New USER
        Else
            mainObj = USERService.GetUSER(RequestContext.UserID)
            If mainObj Is Nothing Then
                Utilities.ShowMessagePage("Failed to load! User may be deleted or not found")
                Return False
            Else
                If mainObj.IS_ADMIN Then
                    Utilities.ShowMessagePage("You are not allow to modify")
                    Return False
                End If
            End If
        End If

        Return True
    End Function

    Private Sub UpdateData(ByVal bSave As Boolean)
        If (bSave) Then
            mainObj.NAME = txtLoginName.Text
            mainObj.LOGIN_NAME = txtLoginName.Text
            mainObj.EMAIL = ""
            mainObj.USER_TYPE = Convert.ToByte(ddlUserType.SelectedItem.Value)
            mainObj.IS_ADMIN = False
            mainObj.IS_ENABLED = True
            mainObj.ActiveOfficeID = 0
            If (IsAddNew OrElse (IsAddNew = False And chkChangePass.Checked)) Then
                mainObj.PASSWORD = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "md5")
            End If
            mainObj.FullPassword = txtFullPassword.Text
            mainObj.CountryID = Convert.ToInt32(ddlCountry.SelectedItem.Value)
            mainObj.ViewSalesOrders = chkViewSalesOrders.Checked
        Else
            txtLoginName.Text = mainObj.LOGIN_NAME
            ddlUserType.SelectedIndex = ddlUserType.Items.IndexOf(ddlUserType.Items.FindByValue(mainObj.USER_TYPE.ToString()))
            txtFullPassword.Text = mainObj.FullPassword
            Try
                ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByValue(mainObj.CountryID.ToString()))
            Catch ex As Exception
            End Try
            chkViewSalesOrders.Checked = mainObj.ViewSalesOrders
        End If
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If RequestContext.CurrentUser.IS_ADMIN = False Then
            btnDelete.Visible = False

        End If
        If Not IsPostBack Then
            ReferrerUrl = Utilities.GetReferrerUrl("UserList.aspx")

            chkOffices.DataSource = OfficeService.GetOffices(OfficeColumns.OfficeID, MyFramework.OrderDirection.ASC)
            chkOffices.DataTextField = OfficeColumns.OfficeName.ToString()
            chkOffices.DataValueField = OfficeColumns.OfficeID.ToString()
            chkOffices.DataBind()

            ddlCountry.DataSource = CountryService.GetCountries(CountryColumns.CountryCode, MyFramework.OrderDirection.ASC)
            ddlCountry.DataTextField = CountryColumns.CountryName.ToString()
            ddlCountry.DataValueField = CountryColumns.CountryID.ToString()
            ddlCountry.DataBind()
            ddlCountry.Items.Insert(0, New ListItem("-- select country --", Nulls.NullInteger.ToString()))

            reqvCountry.InitialValue = Nulls.NullInteger.ToString()

            If IsAddNew Then
                chkChangePass.Visible = False
            Else
                If (BuildObject()) Then
                    UpdateData(False)
                    Dim officeCol As OfficeCollection = OfficeService.GetOffices(mainObj.US_ID_PK)

                    For Each officeObj As Office In officeCol
                        Try
                            chkOffices.Items.FindByValue(officeObj.OfficeID.ToString()).Selected = True
                        Catch ex As Exception

                        End Try
                    Next
                End If
                btnDelete.Attributes("onclick") = "return confirm('Are you sure you want to delete?');"
                btnDelete.Visible = True
            End If

            If (RequestContext.CurrentUser.IS_ADMIN) Then
                ddlUserType.Items.Insert(0, New ListItem("Manager", "5"))
            End If
        End If
    End Sub

    Private Function IsUserExisted() As Boolean
        Dim dummy As USER = USERService.GetUSER(mainObj.LOGIN_NAME)
        If Not (dummy Is Nothing) Then
            ltrMessage.Text = "Login name has already existed. Please enter another."
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        If (Page.IsValid) Then
            If (BuildObject()) Then
                Dim oldLoginName As String = mainObj.LOGIN_NAME
                UpdateData(True)
                If IsAddNew Then
                    If IsUserExisted() = True Then Return
                    USERService.CreateUSER(mainObj)
                Else
                    If Not oldLoginName.ToLower().Trim().Equals(mainObj.LOGIN_NAME.ToLower().Trim()) Then
                        If IsUserExisted() = True Then Return
                    End If
                    USERService.UpdateUSER(mainObj)
                End If

                Dim officeCol As OfficeCollection = OfficeService.GetOffices(mainObj.US_ID_PK)

                For Each officeObj As Office In officeCol
                    UserOfficeService.DeleteUserOffice(officeObj.OfficeID, mainObj.US_ID_PK)                    
                Next

                For Each chkOffice As ListItem In chkOffices.Items
                    If (chkOffice.Selected = True) Then
                        Dim uOffice As UserOffice = New UserOffice
                        uOffice.OfficeID = Convert.ToInt32(chkOffice.Value)
                        uOffice.UserID = mainObj.US_ID_PK
                        UserOfficeService.CreateUserOffice(uOffice)
                    End If
                Next

                Response.Redirect(ReferrerUrl)
            End If
        End If
    End Sub

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
        USERService.DeleteUSER(RequestContext.UserID)
        Response.Redirect(ReferrerUrl)
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Response.Redirect(ReferrerUrl)
    End Sub
End Class
